package com.zzl.mine.controller.api.mail;

import com.gitee.yongzhuzl.commonutil.util.mail.mo.AttachBean;
import com.gitee.yongzhuzl.commonutil.util.mail.mo.Mail;
import com.gitee.yongzhuzl.commonutil.util.mail.mo.MailUtil;
import com.gitee.yongzhuzl.commonutil.util.properties.PropertiesUtil;
import com.gitee.yongzhuzl.commonutil.util.result.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.Session;
import java.io.File;
import java.text.MessageFormat;
import java.util.Map;
import java.util.UUID;

/**
 * Description：发送邮件controller
 * Created by 朱正磊 on 2019-07-20 17:39
 */
@SuppressWarnings("ALL")
@Controller
public class MailController {

    @RequestMapping(value = "/mail/send", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult sendMail() {
        //1、获取配置信息
        Map<String, String> prop = PropertiesUtil.getAllProperties("resource/mail.properties");

        //2、登录邮件服务器，得到Session
        String host = prop.get("host");//服务器主机名
        String username = prop.get("username");//用户名
        String password = prop.get("password");//用户密码
        Session session = MailUtil.createSession(host, username, password);

        //3、创建Mail对象
        String from = prop.get("from");//发件人
        String to = "2474089165@qq.com";//收件人
        String subject = prop.get("subject");//主题
        //MessageFormat.format()的用法举例说明，MessageFormat.format("He is {0}, he is {1}.", "lisi", "happy");返回He is lisi, he is happy.
        String content = MessageFormat.format(prop.get("content"), UUID.randomUUID().toString());//内容
        Mail mail = new Mail(from, to, subject, content);//创建Mail对象
        mail.addAttach(new AttachBean(new File("E:\\qqpic\\xxqe.jpg"), "小企鹅"));

        //4、发送邮件
        try {
            MailUtil.send(session, mail);
        } catch (Exception e) {
            throw new RuntimeException(e);//抛出运行时异常
        }

        return ResponseResult.buildResult("发送邮件成功！");
    }

}
